package top.ajun.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus配置
 *
 * @author AJun
 * @date 2020/12/1
 */
@Configuration
@MapperScan("top.ajun.modules.*.dao") // Mapper 扫描包
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 自动填充策略
     */
    @Component
    static class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
        /**
         * 插入时的填充策略 => gmtCreate, gmtUpdate
         */
        @Override
        public void insertFill(MetaObject metaObject) {
            boolean gmtCreateFlag = metaObject.hasSetter("gmtCreate");
            boolean gmtUpdateFlag = metaObject.hasSetter("gmtUpdate");
            if (gmtCreateFlag)
                this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now());
            if (gmtUpdateFlag)
                this.strictInsertFill(metaObject, "gmtUpdate", LocalDateTime.class, LocalDateTime.now());
        }

        /**
         * 更新时的填充策略 => gmtUpdate
         */
        @Override
        public void updateFill(MetaObject metaObject) {
            boolean gmtUpdateFlag = metaObject.hasSetter("gmtUpdate");
            if (gmtUpdateFlag)
                this.strictUpdateFill(metaObject, "gmtUpdate", LocalDateTime.class, LocalDateTime.now());
        }
    }

}
